package org.jeecg.modules.demo.caiWuSrOrder.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.caiWuSrOrder.entity.CwSrOrder;
import org.jeecg.modules.demo.caiWuSrOrder.service.ICwSrOrderService;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.util.generateOddUtilXs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

 /**
 * @Description: 销售收入单
 * @Author: jeecg-boot
 * @Date:   2021-12-14
 * @Version: V1.0
 */
@Api(tags="销售收入单")
@RestController
@RequestMapping("/sale/cwSrOrder")
@Slf4j
public class CwSrOrderController extends JeecgController<CwSrOrder, ICwSrOrderService> {
	@Autowired
	private ICwSrOrderService cwSrOrderService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private ISoSaleOrderService soSaleOrderService;

	 private static final String TITLE = "单据审核";

	 private String getMessage(String name,String date) {
		 String str ="由【"+name+"】于【"+date+"】发起的收入单需要您的审核，请及时查看！";
		 return str;
	 }
	/**
	 * 分页列表查询
	 *
	 * @param cwSrOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "销售收入单-分页列表查询")
	@ApiOperation(value="销售收入单-分页列表查询", notes="销售收入单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/income/CwSrOrderList")
	public Result<?> queryPageList(CwSrOrder cwSrOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CwSrOrder> queryWrapper = QueryGenerator.initQueryWrapper(cwSrOrder, req.getParameterMap());
		queryWrapper.eq("IS_DELETE",0);
		Page<CwSrOrder> page = new Page<CwSrOrder>(pageNo, pageSize);
		IPage<CwSrOrder> pageList = cwSrOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param
	 * @return
	 */
	@AutoLog(value = "销售收入单-添加")
	@ApiOperation(value="销售收入单-添加", notes="销售收入单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			CwSrOrder cwSrOrder = JSON.parseObject(jsonObject.toJSONString(), CwSrOrder.class);
			SoSaleOrder soSaleOrder = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
			SimpleDateFormat soSettlementf = new SimpleDateFormat("yyyyMMdd");
			String uid_pefix = soSettlementf.format(new Date());
			List<CwSrOrder> list = this.cwSrOrderService.list();
			Collections.sort(list);

			String max_code = "";
			if(list.size() > 0){
				max_code = list.get(0).getSrNo();
			}
			Map<String,String> codeMap = new HashMap<>();
			if(max_code == null){
				codeMap.put("maxCode",null);
			}else{
				codeMap.put("maxCode",max_code);
			}
			String tenantId = req.getHeader("tenant-id");
			String tname = soSaleOrderService.getTname(tenantId);
			String xssr = generateOddUtilXs.createCode(codeMap,tname+"SR_");

			cwSrOrder.setId("");
			cwSrOrder.setXm(soSaleOrder.getProject());
			cwSrOrder.setYwName(soSaleOrder.getSoStaff());
			cwSrOrder.setSrNo(xssr);
			if (cwSrOrder.getPuCdate() == null){
				cwSrOrder.setPuCdate(new Date());
			}
			cwSrOrder.setSoStatus(0);
			cwSrOrder.setIsDelete(0);
			cwSrOrderService.save(cwSrOrder);

			LoginUser user = sysBaseAPI.getUserById(cwSrOrder.getYwName());
			TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
			templateMessageDTO.setFromUser("管理员");
			templateMessageDTO.setToUser(cwSrOrder.getShName()+",");
			templateMessageDTO.setTitle(TITLE);
			templateMessageDTO.setTemplateCode("order");
			Map<String, String> templateParam = new HashMap<>();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String str= simpleDateFormat.format(new Date());
			templateParam.put("ts_date",str);
			templateParam.put("ts_content",getMessage(user.getRealname(),str));
			templateParam.put("checkOrder",cwSrOrder.getSrNo());
			templateParam.put("cd_url","/income/CwSrOrderList/list");
			templateMessageDTO.setTemplateParam(templateParam);
			sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

			return Result.OK("生成收入单成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("操作失败");
		}
	}

	/**
	 *  编辑
	 *
	 * @param cwSrOrder
	 * @return
	 */
	@AutoLog(value = "销售收入单-编辑")
	@ApiOperation(value="销售收入单-编辑", notes="销售收入单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CwSrOrder cwSrOrder) {
		cwSrOrder.setCreateTime(new Date());
		cwSrOrderService.updateById(cwSrOrder);
		return Result.OK("编辑成功!");
	}

	 @PutMapping(value = "/editShenhe")
	 public Result<?> editShenhe(@RequestBody CwSrOrder cwSrOrder) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if (!cwSrOrder.getShName().equals(sysUser.getId())){
			 return Result.error(300,"您不是当前单据的指定审核人！");
		 }
		 if (cwSrOrder.getSoStatus() == 1) {
//			 cwSrOrder.setShName(sysUser.getRealname());
			 cwSrOrder.setShTime(new Date());
		 } else {
//			 cwSrOrder.setShName("");
			 cwSrOrder.setShTime(null);
		 }
		 cwSrOrder.setCreateTime(new Date());
		 cwSrOrderService.updateById(cwSrOrder);
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售收入单-通过id删除")
	@ApiOperation(value="销售收入单-通过id删除", notes="销售收入单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			CwSrOrder cwSrOrder = cwSrOrderService.getById(id);
			if(cwSrOrder.getSoStatus()==1){
				return Result.error(500,"单据已审核，无法删除！");
			}
			cwSrOrderService.removeById(id);
			return Result.OK("删除成功!");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}

	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "销售收入单-批量删除")
	@ApiOperation(value="销售收入单-批量删除", notes="销售收入单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cwSrOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "销售收入单-通过id查询")
	@ApiOperation(value="销售收入单-通过id查询", notes="销售收入单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CwSrOrder cwSrOrder = cwSrOrderService.getById(id);
		if(cwSrOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cwSrOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cwSrOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CwSrOrder cwSrOrder) {
        return super.exportXls(request, cwSrOrder, CwSrOrder.class, "销售收入单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CwSrOrder.class);
    }

}
